package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.constant.RedisConstants;
import com.hmdp.constant.SystemConstants;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            //查询blog的用户
            queryBlogUser(blog);

            //查询blog是否被点赞了
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        //查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }

        //查询blog的用户
        queryBlogUser(blog);

        //查询blog是否被点赞了
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO userDTO = UserHolder.getUser();
        if (userDTO == null) {
            //用户未登录，无需查询用户是否点赞
            return;
        }
        Long userId = userDTO.getId();
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.RedisBlogConstants.BLOG_LIKED_KEY_PREFIX + blog.getId(), userId.toString());
        blog.setIsLike(score != null);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public Result likeBlog(Long id) {
        Long userId = UserHolder.getUser().getId();
        //zcore key member1
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.RedisBlogConstants.BLOG_LIKED_KEY_PREFIX + id, userId.toString());

        if (score == null) {
            //1、用户未点赞：点赞数+1，保存用户到redis集合
            boolean isSuccess = update()
                    .setSql("liked = liked + 1")
                    .eq("id", id)
                    .update();
            if (isSuccess) {
                // zadd key member1 member1Score
                stringRedisTemplate.opsForZSet().add(RedisConstants.RedisBlogConstants.BLOG_LIKED_KEY_PREFIX + id, userId.toString(),System.currentTimeMillis());
            }
        }else {
            //2、用户已经点赞：点赞数-1，从redis集合移除用户
            boolean isSuccess = update()
                    .setSql("liked = liked - 1")
                    .eq("id", id)
                    .update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(RedisConstants.RedisBlogConstants.BLOG_LIKED_KEY_PREFIX + id, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //查询top5的点赞用户id zrange key 0 4
        Set<String> top5UserIdSet = stringRedisTemplate.opsForZSet().range(RedisConstants.RedisBlogConstants.BLOG_LIKED_KEY_PREFIX + id, 0, 4);
        if (CollectionUtil.isEmpty(top5UserIdSet)) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> userIds = top5UserIdSet.stream().map(Long::valueOf).collect(Collectors.toList());
        String userIdStr = StrUtil.join(",", userIds);

        //根据用户id查询用户
        List<User> userList = userService.query()
                .in("id", userIds)
                .last("order by FIELD(id,"+userIdStr+")")
                .list();
        List<UserDTO> userDTOList = userList.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOList);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("新增比较失败！");
        }

        // 查询当前用户的粉丝 select * from tb_follow where follow_user_id = ?
        List<Follow> followList = followService.query()
                .eq("follow_user_id", user.getId())
                .list();
        for (Follow follow : followList) {
            // 推送笔记的id给粉丝的收件箱
            Long userId = follow.getUserId();
            stringRedisTemplate.opsForZSet().add(RedisConstants.RedisFeedConstants.FEED_KEY_PREFIX+userId.toString(), blog.getId().toString(),System.currentTimeMillis());
        }

        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        Long userId = UserHolder.getUser().getId();

        //查询收件箱
        //第一次：zrevrangebyscore feed:1 当前时间戳 0 withscores limit 0 页大小
        //下次：zrevrangebyscore feed:1 上一次查询的最小的时间戳 0 withscores limit 上一次查询的最小的时间戳想同的个数 页大小
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(
                RedisConstants.RedisFeedConstants.FEED_KEY_PREFIX + userId,
                0,
                max,
                offset,
                2
        );
        if(CollUtil.isEmpty(typedTuples)){
            return Result.ok();
        }

        //解析数据：blogId、minTime、offset
        List<Long> blogIds = new ArrayList<>();
        long minTime = 0;
        int returnOffset = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //blogId
            String blogIdStr = typedTuple.getValue();
            blogIds.add(Long.valueOf(blogIdStr));
            //时间戳
            long timestamp = typedTuple.getScore().longValue();
            //returnOffset
            if(timestamp == minTime){
                returnOffset++;
            }else {
                //minTime
                minTime = timestamp;
                returnOffset = 1;
            }
        }
        //根据blogId查询Blog
        String blogIdStr = StrUtil.join(",", blogIds);
        List<Blog> blogList = query()
                .in("id", blogIds)
                .last("order by FIELD(id," + blogIdStr + ")")
                .list();
        for (Blog blog : blogList) {
            //查询blog的用户
            queryBlogUser(blog);

            //查询blog是否被点赞了
            isBlogLiked(blog);
        }

        //封装结果
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(returnOffset);
        return Result.ok(scrollResult);
    }
}
